﻿using Furion.HttpRemote;
using Furion;
using ST.Torch.WebApi.Application.System.Services;
using ST.Torch.WebApi.Application.Utils.Dtos;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ST.Torch.WebApi.Core.Entities.DaTi;

namespace ST.Torch.WebApi.Application.WebSize
{
    public class TorchAppService : IDynamicApiController
    {
        private readonly ISYSUserService _SYSUserService;
        private readonly IUIDService _UIDService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private IRepository _repository;
        public string appid = App.GetConfig<string>("WeChat:appid");
        public string appsecret = App.GetConfig<string>("WeChat:appsecret");
        /// <summary>
        /// 
        /// </summary>
        /// <param name="SYSUserService"></param>
        /// <param name="UIDService"></param>
        /// <param name="httpContextAccessor"></param>
        /// <param name="repository"></param>
        public TorchAppService(ISYSUserService SYSUserService, IUIDService UIDService, IHttpContextAccessor httpContextAccessor, IRepository repository)
        {

            _SYSUserService = SYSUserService;
            _UIDService = UIDService;
            _httpContextAccessor = httpContextAccessor;
            _repository = repository;   
        }

        /// <summary>
        /// 小程序获取openId
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<string> GetOpenid(string code)
        {
            var _httpRemoteService = App.GetService<IHttpRemoteService>();
            string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={appsecret}&js_code={code}&grant_type=authorization_code";
            var res = await _httpRemoteService.GetAsync(url);
            string content = await res.Content.ReadAsStringAsync();
            var tempData = JsonConvert.DeserializeObject<jscode2sessionModel>(content);

            return tempData.openid;

        }
        /// <summary>
        /// 获取题目
        /// </summary>
        /// <param name="nubmer"></param>
        /// <returns></returns>
        public async Task<List<D_TiMu>> GetTopic(int nubmer=3)
        {
            var Datas= await _repository.Change<D_TiMu>().Where(u => true,false).ToListAsync();
            List<D_TiMu> ResData=new List<D_TiMu>();
            for (int i=1;i<=nubmer;i++) 
            { 
                Random random = new Random();
                var index=random.Next(Datas.Count()-1);
                ResData.Add(Datas[index].Adapt<D_TiMu>());
                Datas.Remove(Datas[index]);
            }
            return ResData;

        }
        /// <summary>
        /// 获取公司
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        public async Task<D_Company> GetCompany(string Code )
        {
            var data= await _repository.Change<D_Company>().FirstOrDefaultAsync(u => u.Code==Code, false);
            return data;
        }
        /// <summary>
        /// 获取所有公司
        /// </summary>
        /// <returns></returns>
        public async Task<List<D_Company>> GetAllCompany()
        {
            var data = await _repository.Change<D_Company>().Where(u => true, false).ToListAsync();
            return data;
        }
        /// <summary>
        /// 所有分行参加人数
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetUserCount()
        {
            var data = await _repository.Change<D_UserInfor>().CountAsync();
            return data;
        }

        /// <summary>
        /// 我的奖品
        /// </summary>
        /// <param name="OpenId"></param>
        /// <returns></returns>
        public async Task<D_UserInfor> GetUserById(string OpenId)
        {
            var data = await _repository.Change<D_UserInfor>().FirstOrDefaultAsync(u => u.OpenId == OpenId, false);
           if(data!=null&&!string.IsNullOrEmpty(data.G_ImgUrl))
                data.G_ImgUrl = data.G_ImgUrl.Replace("\\", "/");

            return data;
        }

        /// <summary>
        /// 全部答对提交
        /// </summary>
        /// <param name="OpenId"></param>
        /// <param name="CompanyCode"></param>
        /// <param name="Starte">0 参与中：1 答题完成</param>
        /// <returns></returns>
        [Post]
        public async Task<bool> SubmitTiMu([FromForm]string OpenId, [FromForm]string CompanyCode, [FromForm] int Starte)
        {
            bool res = false;
            if (string.IsNullOrEmpty(OpenId)) return res;
            var Company = await _repository.Change<D_Company>().FirstOrDefaultAsync(u => u.Code == CompanyCode, false);
            var user = await _repository.Change<D_UserInfor>().FirstOrDefaultAsync(u => u.OpenId == OpenId);
            if (Company == null) return res;
            if (Starte == 0)
            {
                if (user == null)
                {
                     user = new D_UserInfor();
                    user.OpenId = OpenId;
                    user.C_Code = CompanyCode;
                    user.C_Name = Company.Name;
                    user.Starte = Starte;
                    await _repository.Change<D_UserInfor>().InsertNowAsync(user);
                }
                return true;
            }
            else
            {
               
               
                user.Starte = Starte;
                res = true;
                //var GiftS = await _repository.Change<D_Gift>().AsQueryable(false).ToListAsync();
                //if (GiftS.Count > 0)
                //{
                //    Random random = new Random();
                //    var index = random.Next(GiftS.Count() - 1);
                //    var gift = GiftS[index];
                //    user.G_ImgUrl = gift.GiftImgUrl;
                //    user.G_Name = gift.Name;
                //    gift.RemainingNumber = gift.RemainingNumber - 1;
                //    await _repository.Change<D_Gift>().UpdateIncludeNowAsync(gift, new string[] { nameof(gift.RemainingNumber) });

                //    res = true;
                //}
                await _repository.Change<D_UserInfor>().UpdateAsync(user);
            }
           
           
           
            
            return res;
        }

        /// <summary>
        /// 活动时间
        /// </summary>
        /// <returns></returns>
        public string GetActionTime()
        {
            return App.GetConfig<string>("SysInfo:ActionTime");
        }


    
        public async Task<dynamic> GetTotalNumber()
        {
            var query =await _repository.Change<D_UserInfor>().AsQueryable().GroupBy(x => new { x.C_Name }).Select(u=> new { number = u.Count(), name = u.Key.C_Name }).ToListAsync();
            int total = query.Sum(u => u.number);
            var Companys=await _repository.Change<D_Company>().AsQueryable().OrderBy(u=>u.Code).ToListAsync();
            List<object> Datas = new List<object>();
            foreach (var item in Companys)
            {
                var Qitem = query.FirstOrDefault(u => u.name == item.Name);
               if (Qitem==null)
                {
                    Datas.Add(new { number = 0, name = item.Name });
                }
                else
                {
                    Datas.Add(new { number = Qitem.number, name = Qitem.name });
                }
            }
            return new { total = total, data = Datas } ;
        }


    }
}
